package com.io.bio;

import com.io.util.CalculatorUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * 任务处理类
 *
 * @author hjj
 * @create 2019-11-22 20:55
 */
public class BIOServerHandler implements Runnable {

    private Socket socket;

    public BIOServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader reader = null;
        PrintWriter writer = null;
        try {
            reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            writer = new PrintWriter(this.socket.getOutputStream());
            // 加上这行代码，会导致程序无法进行
//            System.out.println("打印客户端传来的数据：" + reader.readLine());
            String body = null;
            while (true) {
                // 若客户端用的是writer.print()传值，那readerLine()是不能获取值，细节
                body = reader.readLine();
                if (body == null) break;
                System.out.println("BIOServer receive: " + body);
                String sendMessage = body + " = " + CalculatorUtil.cal(body).toString();
                System.out.println("BIOServer send: " + sendMessage);
                writer.println(sendMessage);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();

            try {
                if (reader != null) reader.close();
                if (socket != null) {
                    socket.close();
                    socket = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }
}
